package com.pigs.springbootpigsvuecrud.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author PIGS-猪农·杨
 * @version 1.0
 * @date 2020/3/6 18:25
 * @effect 时间 工具类
 */
public class TimeUtitl {

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String dateTime() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeFormat = simpleDateFormat.format(date);
        return timeFormat;
    }

    public static String getTime() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String timeFormat = simpleDateFormat.format(date);
        return timeFormat;
    }

    /**
     * 计算年龄
     *
     * @param birthDay
     * @return
     * @throws Exception
     */
    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();
        /**
         * 出生日期晚于当前时间，无法计算
         */
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "出生日期晚于当前时间，无法计算!");
        }
        /**
         * 当前年份
         * 当前月份
         * 当前日期
         */
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        /**
         * 计算整岁数
         * 当前日期在生日之前，年龄减一
         * 当前月份在生日之前，年龄减一
         */
        int age = yearNow - yearBirth;
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                age--;

            }
        }
        return age;
    }

    /**
     * 把出生日期字符串转换为日期格式。
     *
     * @param strDate
     * @return
     * @throws ParseException
     */
    public static Date parse(String strDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(strDate);
    }


}
